<?php

namespace app\middleware;

use common\service\JwtService;
use ReflectionClass;
use ReflectionException;
use core\exception\BadException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class ApiAuthMiddleware implements MiddlewareInterface
{
    const ALL_AUTH = "*";
    const AUTH_KEY = "Authorization";

    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws BadException
     * @throws ReflectionException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function process(Request $request, callable $handler): Response
    {
        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);

        $prop = $controller->getDefaultProperties();
        $noNeedLogin = $prop['noNeedLogin'] ?? [];
        $token = trim(str_replace("Bearer","",$request->header(self::AUTH_KEY)));
        //C端需要兼容某些接口可以登录也可以不登录
        $user=[];
        if ($token){
            $user = JwtService::verifyToken($token,'api');
        }
        $request->uid = $user['id'] ?? 0;

        if (in_array(self::ALL_AUTH, $noNeedLogin) || in_array($request->action, $noNeedLogin)) {
            return $handler($request);
        }

        if (!$token || !$user) {
            throw new BadException("登录异常", 401);
        }
        return $handler($request);
    }

}
